<!--
 * @Description: 售后回访录入
 * @Autor: 刘诗文
 * @Date: 2020-12-01 20:22:02
 * @LastEditors: 马毅
 * @LastEditTime: 2021-07-07 21:58:05
-->
<template>
  <div>
    <el-tabs v-model="activeTab">
      <el-tab-pane label="提醒信息" :name="'reminders'">
        <FormPanel ref="formPanel" :list="formList" :cols="3" :labelWidth="130" :formType="type" :isSubmitBtn="false" />
        <FilterTable
          ref="table"
          height="400"
          selectionType="single"
          :columns="columns"
          :fetchapi="fetchApiAsk"
          :datakey="'rows'"
          :onSyncTableData="tableDataChangeMeth"
          :params="getAskAndAnswerInfoParams"
          columnsRef="afterRemindInputslsw"
          :onColumnsChange="columns => (this.columns = columns)"
          :onRowSelectChange="onRowSelectChange"
        >
          <template slot="controls">
            <el-button size="small" type="primary" @click="() => this.openHandler('reminders', {})">提示/预警信息</el-button>
            <el-button size="small" type="primary" @click="() => this.openHandler('complaintHistory', {})">投诉历史</el-button>
            <el-button size="small" type="primary" @click="() => this.openHandler('repairHistory', {})">维修历史</el-button>
            <el-button size="small" type="primary" @click="() => this.openHandler('remindHistory', {})">提醒历史</el-button>
            <el-button size="small" type="primary" @click="() => this.openHandler('maintenanceAdvice', {})">维修建议</el-button>
          </template>
        </FilterTable>
        <FormPanel ref="formPanel_trackingRecord" :list="formListTrackingRecord" :cols="4" :labelWidth="130" :formType="type" :isSubmitBtn="false" />
        <FilterTable
          ref="table_trackingRecord"
          height="200"
          selectionType="single"
          :columns="columnsTrackingRecord"
          :datakey="'rows'"
          :dataSource="tableList"
          :isMemoryPagination="true"
          columnsRef="afterRemindInputsTrackingRecordlsw"
          :onColumnsChange="columnsTrackingRecord => (this.columnsTrackingRecord = columnsTrackingRecord)"
          :onRowSelectChange="onRowSelectChangeTrackingRecord"
          :onSyncTableData="tableHandle"
        >
          <template slot="controls">
            <el-button size="small" type="primary" icon="el-icon-plus" :disabled="trackingRecordButton" @click="addTrackingRecord">新增</el-button>
          </template>
        </FilterTable>
        <ButtonArea :containerStyle="{ display: 'flex', justifyContent: 'center' }">
          <el-button type="primary" @click="() => this.openHandler('appointment', {})">预约安排</el-button>
          <AjaxButton type="primary" :disabled="remindInputsButton" :click="saveHandle">确 定</AjaxButton>
          <el-button type="primary" @click="cancelHandle">取 消</el-button>
        </ButtonArea>
      </el-tab-pane>
      <el-tab-pane label="工单历史" :name="'orderHistory'">
        <FilterTable
          ref="roHistory"
          columnsRef="roHistorylsw"
          height="500"
          :dataSource="roHistoryList"
          :columns="roHistoryColumns"
          :onColumnsChange="columns => (this.roHistoryColumns = columns)"
          :onSyncTableData="roHistoryTableChange"
        >
        </FilterTable>
      </el-tab-pane>
      <!-- <el-tab-pane label="服务活动" :name="'serviceActivities'">
        <FilterTable
          ref="activity"
          columnsRef="activitylsw"
          height="500"
          :datakey="'records'"
          :columns="activityColumns"
          :fetchapi="fetchApiActivity"
          :params="fetchParamsActivity"
          :onColumnsChange="columns => (this.activityColumns = columns)"
        >
        </FilterTable>
      </el-tab-pane> -->
    </el-tabs>
    <!-- 提示/预警信息 -->
    <BaseDialog
      :visible.sync="remindersActions.visible"
      :title="remindersActions.title"
      width="70%"
      destroyOnClose
      :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }"
    >
      <reminders :type.sync="remindersActions.type" :carInfo="carInfoObj" :vin="carVin" @close="closeHandler_reminders" />
    </BaseDialog>
    <!-- 投诉历史 -->
    <BaseDialog
      :visible.sync="complaintHistoryActions.visible"
      :title="complaintHistoryActions.title"
      width="70%"
      destroyOnClose
      :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }"
    >
      <complaintHistory :type.sync="complaintHistoryActions.type" :vin="carVin" @close="closeHandler_complaintHistory" />
    </BaseDialog>
    <!-- 维修历史-->
    <BaseDialog
      :visible.sync="repairHistoryActions.visible"
      :title="repairHistoryActions.title"
      destroyOnClose
      :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }"
    >
      <repairHistory :carInfo="carInfoObj" :vin="carVin" @close="closeHandler_repairHistory" />
    </BaseDialog>
    <!-- 提醒历史 -->
    <BaseDialog
      :visible.sync="remindHistoryActions.visible"
      :title="remindHistoryActions.title"
      width="70%"
      destroyOnClose
      :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }"
    >
      <remindHistory :type.sync="remindHistoryActions.type" :formData="formData" :vin="carVin" @close="closeHandler_remindHistory" />
    </BaseDialog>
    <!-- 维修建议 -->
    <BaseDialog
      :visible.sync="maintenanceAdviceActions.visible"
      :title="maintenanceAdviceActions.title"
      width="70%"
      destroyOnClose
      :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }"
    >
      <maintenanceAdvice :type.sync="maintenanceAdviceActions.type" :vin="carVin" @close="closeHandler_maintenanceAdvice" />
    </BaseDialog>
    <!--预约安排-->
    <Drawer
      :visible.sync="precontractArrange.visible"
      :title="precontractArrange.title"
      destroyOnClose
      :width="1300"
      :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }"
    >
      <precontractArrange :formData="this.resData" :type.sync="precontractArrange.type" @close="closeHandler_precontractArrange" />
    </Drawer>
  </div>
</template>
<script>
import { dictionary } from '@/utils/dictMixin';
import reminders from './reminders.vue'; // 提示/预警信息
import complaintHistory from '@/pages/repair/repairReception/precontractArrange/complainHistory/index.vue'; // 投诉历史
import repairHistory from '@/pages/repair/repairReception/customer/repairHistory'; // 维修历史
import remindHistory from './remindHistory.vue'; // 提醒历史
import maintenanceAdvice from './maintenanceAdvice.vue'; // 维修建议
import precontractArrange from '@/pages/repair/repairReception/precontractArrange'; // 预约安排
import { visitInputSave, returnHistory, activityList, getAskAndAnswer, getAskAndAnswerInfo } from '@/api/customerRepair/afterSaleVisit/resultEntry';
import { isFormEmpty, notifyAction, camelCaseObject, findTableItem } from '@/utils';
import { getWxlxSelect, queryLocalRepairHistory } from '@/api/repair/repairReception/customer';
import Cookies from 'js-cookie';
export default {
  name: 'afterRemindInputs',
  components: {
    reminders,
    complaintHistory,
    repairHistory,
    remindHistory,
    maintenanceAdvice,
    precontractArrange
  },
  mixins: [dictionary],
  props: {
    type: {
      type: String
    },
    formData: {
      type: Object,
      default: () => ({})
    }
  },
  data() {
    this.selectedData = null;
    this.BaseTable = null;
    this.selectedDataTrackingRecord = null;
    this.resData = {};
    return {
      formList: this.createFromList(),
      columns: this.createTableColumns(),
      formListTrackingRecord: this.createFromListTrackingRecord(),
      columnsTrackingRecord: this.createTableColumnsTrackingRecord(),
      roHistoryColumns: this.createTableColumnsRoHistory(),
      activityColumns: this.createTableColumsActivity(),
      tableParamData: {},
      fetchApiAsk: getAskAndAnswerInfo,
      getAskAndAnswerInfoParams: { xhrAbort: true },
      tableDataChange: [],
      activeTab: 'reminders',
      remindersActions: { type: '', visible: false, title: '' }, // 提示/预警信息
      complaintHistoryActions: { type: '', visible: false, title: '' }, // 投诉历史
      repairHistoryActions: { type: '', visible: false, title: '' }, // 维修历史
      remindHistoryActions: { type: '', visible: false, title: '' }, // 提醒历史
      maintenanceAdviceActions: { type: '', visible: false, title: '' }, // 维修建议
      precontractArrange: { type: '', visible: false, title: '' }, // 预约安排
      tableList: [],
      roHistoryList: [], // 工单历史集合
      activityList: [], // 服务活动集合
      fetchApiActivity: activityList,
      fetchParamsActivity: { vin: this.formData.vin, appId: Cookies.get('appId'), resDealer: Cookies.get('ownerCode') },
      remindInputsButton: false, // 问卷录入按钮是否只读
      trackingRecordButton: false, // 跟踪table新增按钮是否只读
      carVin: '', // 维修历史需要底盘号参数
      carInfoObj: {} // 维修历史需要的对象
    };
  },
  mounted() {
    this.BaseTable = this.$refs.table;
    this.BaseTableTrackingRecord = this.$refs.table_trackingRecord;
    // 获取维修类型
    this.queryRepairTypeDict();
    if (this.formData.trackStatus != 80581001) {
      this.getTrackHistory();
    }
    if (this.type === 'show') {
      this.remindInputsButton = true;
      this.trackingRecordButton = true;
    }
    //获取问卷
    this.getAnswer();
    // 初始化
    this.init();
    this.selectQuestionnaire(this.formData.chooseAnswer);
  },
  methods: {
    createFromList() {
      return [
        {
          type: 'INPUT',
          label: '车主',
          fieldName: 'ownerName',
          disabled: true,
          initialValue: this.formData.ownerName
        },
        {
          type: 'INPUT',
          label: '送修人',
          fieldName: 'deliverer',
          disabled: true,
          initialValue: this.formData.deliverer
        },
        {
          type: 'INPUT',
          label: '车牌号',
          fieldName: 'license',
          disabled: true,
          initialValue: this.formData.license
        },
        {
          type: 'INPUT',
          label: 'VIN',
          fieldName: 'vin',
          disabled: true,
          initialValue: this.formData.vin
        },
        {
          type: 'INPUT',
          label: '车主电话',
          fieldName: 'phone',
          disabled: true,
          initialValue: this.formData.phone
        },
        {
          type: 'INPUT',
          label: '送修人手机',
          fieldName: 'delivererPhone',
          disabled: true,
          initialValue: '',
          initialValue: this.formData.delivererMobile
        },
        {
          type: 'INPUT',
          label: '车型',
          fieldName: 'brandName',
          disabled: true,
          initialValue: this.formData.brandName
        },
        {
          type: 'INPUT',
          label: '服务顾问',
          fieldName: 'serviceAdvisor',
          disabled: true,
          initialValue: this.formData.serviceAdvisor
        },
        // {
        //   type: 'DATE',
        //   label: '保险到期日期',
        //   fieldName: 'expiredDate',
        //   disabled: true,
        //   initialValue: ''
        // },
        // {
        //   type: 'SELECT',
        //   label: '保险公司',
        //   fieldName: 'insurationCode',
        //   disabled: true,
        //   itemList: this.createDictList(9607).map(item => ({ text: item.text, value: item.value + '' })),
        //   initialValue: ''
        // },
        // {
        //   type: 'INPUT',
        //   label: '本店最近购买保险日',
        //   fieldName: 'instruaBuyDate',
        //   disabled: true,
        //   initialValue: ''
        // },
        {
          type: 'SELECT',
          label: '选择回访问卷',
          fieldName: 'chooseAnswer',
          itemList: [],
          initialValue: this.formData.chooseAnswer,
          disabled: this.type === 'show' ? true : false,
          change: val => {
            this.selectQuestionnaire(val);
          }
        }
      ];
    },
    createTableColumns() {
      return [
        {
          title: '序号',
          dataIndex: 'index',
          width: 70,
          render: props => {
            return <span>{props.row.index + 1}</span>;
          }
        },
        {
          title: '问题代码',
          dataIndex: 'WXWTDM',
          width: 300,
          showOverFlowTip: true
        },
        {
          title: '问题内容',
          dataIndex: 'WXWTNR',
          width: 300,
          showOverFlowTip: true
        },
        {
          title: '问题类型',
          dataIndex: 'WXWTLX',
          width: 120,
          dictItems: this.createDictList('5018'),
          showOverFlowTip: true
        },
        {
          title: '答案',
          dataIndex: 'WXGLXH',
          width: 500,
          showOverFlowTip: true,
          render: props => {
            switch (props.row.WXWTLX) {
              case 50181001:
                let options1 = props.row.chooseList.map(item => <el-option key={item.value} label={item.text} value={item.value + ''}></el-option>);
                return <el-select v-model={props.row.WXGLXH}>{options1}</el-select>;
              case 50181002:
                let options = props.row.chooseList.map(item => <el-option key={item.value} label={item.text} value={item.value + ''}></el-option>);
                return (
                  <el-select multiple v-model={props.row.WXGLXH}>
                    {options}
                  </el-select>
                );
              case 50181003:
                return <el-input v-model={props.row.WXGLXH}></el-input>;
            }
          }
        }
      ];
    },
    createFromListTrackingRecord() {
      return [
        {
          type: 'BREAK_SPACE',
          label: '本单跟踪记录'
        },
        {
          type: 'CHECKBOX',
          label: '是否三日电访(车辆)',
          fieldName: 'istrace',
          itemList: this.createDictList(1004),
          disabled: this.type === 'show' ? true : false
        },
        {
          type: 'SELECT',
          label: '跟踪状态',
          fieldName: 'trackStatus',
          itemList: this.createDictList(8058, [80581001]),
          disabled: this.type === 'show' ? true : false,
          rules: [{ required: true, message: '请输入跟踪状态', trigger: 'blur' }],
          change: val => {
            if (val === 80581003) {
              this.formListTrackingRecord.find(x => x.fieldName === 'returnVisitResults').disabled = false;
            } else {
              this.formListTrackingRecord.find(x => x.fieldName === 'returnVisitResults').disabled = true;
              this.formListTrackingRecord.find(x => x.fieldName === 'returnVisitResults').initialValue = '';
            }
            if (val === 80581004) {
              this.formListTrackingRecord.find(x => x.fieldName === 'reasonsFailOfVisit').disabled = false;
            } else {
              this.formListTrackingRecord.find(x => x.fieldName === 'reasonsFailOfVisit').disabled = true;
              this.formListTrackingRecord.find(x => x.fieldName === 'reasonsFailOfVisit').initialValue = '';
            }
          }
        },
        {
          type: 'SELECT',
          label: '回访失败原因',
          fieldName: 'reasonsFailOfVisit',
          disabled: true,
          itemList: this.createDictList(1594)
        },
        {
          type: 'SELECT',
          label: '回访结果',
          fieldName: 'returnVisitResults',
          disabled: true,
          itemList: this.createDictList(8043, [80431002, 80431004])
        },
        // {
        //   type: 'SELECT',
        //   label: '不满意原因',
        //   fieldName: 'returnVisitResults',
        //   itemList: this.createDictList(8043, [80431002, 80431004])
        // },
        {
          type: 'TEXT_AREA',
          label: '备注',
          fieldName: 'remarks',
          selfCols: 2,
          initialValue: '',
          disabled: this.type === 'show' ? true : false
        },
        {
          type: 'TEXT_AREA',
          label: '下次维修提醒',
          fieldName: 'nextMaintenanceReminder',
          selfCols: 2,
          initialValue: '',
          disabled: this.type === 'show' ? true : false
        },
        {
          type: 'TEXT_AREA',
          label: '不满意原因描述',
          fieldName: 'reasonsFailOfVisitInfo',
          selfCols: 2,
          initialValue: '',
          disabled: this.type === 'show' ? true : false
        }
      ];
    },
    createTableColumnsTrackingRecord() {
      return [
        {
          title: '序号',
          dataIndex: 'index',
          width: 70,
          render: props => {
            return <span>{props.row.$index + 1}</span>;
          }
        },
        {
          title: '跟踪时间',
          dataIndex: 'trackDate',
          editType: 'date-picker',
          editable: true,
          dataFormat: 'yyyy-MM-dd HH:mm:ss',
          editRequired: true,
          showOverFlowTip: true
        },
        {
          title: '描述',
          dataIndex: 'describea',
          editType: 'text',
          editable: true,
          editRequired: true,
          showOverFlowTip: true
        }
      ];
    },
    // 工单历史table
    createTableColumnsRoHistory() {
      return [
        {
          title: '序号',
          dataIndex: 'index',
          width: 70,
          render: props => {
            return <span>{props.row.index + 1}</span>;
          }
        },
        {
          title: '工单号',
          dataIndex: 'RO_NO'
        },
        {
          title: '维修类型',
          dataIndex: 'REPAIR_TYPE_CODE',
          dictItems: []
        },
        {
          title: '开单时间',
          dataIndex: 'RO_CREATE_DATE'
        },
        {
          title: '工时费',
          dataIndex: 'LABOUR_AMOUNT'
        },
        {
          title: '维修材料费',
          dataIndex: 'REPAIR_PART_AMOUNT'
        },
        {
          title: '维修总金额',
          dataIndex: 'TOTAL_AMOUNT'
        }
      ];
    },
    // 服务活动table
    createTableColumsActivity() {
      return [
        {
          title: '序号',
          dataIndex: 'index',
          width: 70,
          render: props => {
            return <span>{props.row.index + 1}</span>;
          }
        },
        {
          title: '活动编号',
          dataIndex: 'maNo'
        },
        {
          title: '活动名称',
          dataIndex: 'maTitle'
        },
        {
          title: '活动类型',
          dataIndex: 'a3'
        },
        {
          title: '开始日期',
          dataIndex: 'bDate',
          dateFormat: 'yyyy-MM-dd'
        },
        {
          title: '结束日期',
          dataIndex: 'eDate',
          dateFormat: 'yyyy-MM-dd'
        },
        {
          title: '活动总金额',
          dataIndex: 'a6'
        }
      ];
    },
    onRowSelectChange(row) {
      if (!row.length) {
        this.selectedData = null;
      } else {
        this.selectedData = row[0];
      }
    },
    onRowSelectChangeTrackingRecord(row) {
      if (!row.length) {
        this.selectedDataTrackingRecord = null;
      } else {
        this.selectedDataTrackingRecord = row[0];
      }
    },
    // 初始化
    init() {
      // 工单历史接口
      this.roHistoryListFun();
    },
    // 选择问卷
    async selectQuestionnaire(val) {
      console.log('问卷选择开始');
      this.getAskAndAnswerInfoParams = Object.assign({}, { WXWJID: val, ORDER_NO: this.formData.roNo, xhrAbort: false });
      console.log('问卷选择结束');
    },
    //新增跟踪记录
    addTrackingRecord() {
      this.BaseTableTrackingRecord.EXECUTE_INSERT(this.tableParamData);
      this.trackingRecordButton = true;
    },
    //确定
    async saveHandle() {
      const [err, data] = await this.$refs.formPanel_trackingRecord.GET_FORM_DATA();
      if (err) return;
      if (this.tableList.length > 0) {
        data.trackDate = this.tableList[this.tableList.length - 1].trackDate;
        data.describea = this.tableList[this.tableList.length - 1].describea;
        if (isFormEmpty(data.trackDate)) {
          return notifyAction('跟踪时间不能为空！', 'warning');
        }
        if (isFormEmpty(data.describea)) {
          return notifyAction('跟踪描述不能为空', 'warning');
        }
      } else {
        return notifyAction('请填写跟踪明细', 'warning');
      }
      data.roNo = this.formData.roNo;
      data.chooseAnswer = this.formList.find(x => x.fieldName == 'chooseAnswer').initialValue;
      data.askAndAnswer = this.tableDataChange;
      const res = await visitInputSave({ ...data });
      if (res.resultCode === 200) {
        if (res.errMsg) {
          notifyAction(res.errMsg, 'error');
        } else {
          notifyAction('保存成功！');
          this.cancelHandle();
        }
      }
    },
    //取消
    cancelHandle() {
      this.$emit('close', false);
    },
    // 打开弹窗
    openHandler(type, val) {
      if (isFormEmpty(this.formData.vin)) {
        return notifyAction('车辆VIN不能为空！', 'warning');
      }
      this.carVin = this.formData.vin;
      this.carInfoObj = this.formData;
      if (type === 'reminders') {
        this.remindersActions = { visible: true, title: '提示/预警信息', type: 'show' };
      } else if (type === 'complaintHistory') {
        this.complaintHistoryActions = { type: 'show', visible: true, title: '投诉历史' };
      } else if (type === 'repairHistory') {
        this.repairHistoryActions = { type: 'show', visible: true, title: '维修历史' };
      } else if (type === 'remindHistory') {
        this.remindHistoryActions = { type: 'show', visible: true, title: '提醒历史' };
      } else if (type === 'maintenanceAdvice') {
        this.maintenanceAdviceActions = { type: 'show', visible: true, title: '维修建议' };
      } else if (type === 'appointment') {
        this.precontractArrange = { type: 'add', visible: true, title: '预约安排' };
      }
    },
    // 关闭提示/预警信息
    closeHandler_reminders() {
      this.remindersActions.visible = false;
    },
    // 关闭投诉历史
    closeHandler_complaintHistory() {
      this.complaintHistoryActions.visible = false;
    },
    // 关闭维修历史
    closeHandler_repairHistory() {
      this.repairHistoryActions.visible = false;
    },
    // 关闭提醒历史
    closeHandler_remindHistory() {
      this.remindHistoryActions.visible = false;
    },
    // 关闭维修建议
    closeHandler_maintenanceAdvice() {
      this.maintenanceAdviceActions.visible = false;
    },
    // 关闭预约安排
    closeHandler_precontractArrange() {
      this.precontractArrange = { type: 'add', visible: false, title: '预约安排' };
    },
    // table动态回调函数
    tableHandle(val, isFirst) {
      this.tableList = val;
      for (let i = 0; i < val.length; i++) {
        if (val[i].OWNER_CODE) {
          this.BaseTable.SET_CELL_UNEDITABLE(val[i], 'trackDate', true);
          this.BaseTable.SET_CELL_UNEDITABLE(val[i], 'describea', true);
        }
      }
    },
    // 工单历史table 回调函数
    roHistoryTableChange(val) {
      this.roHistoryList = val;
    },
    // 查询跟踪记录信息
    async getTrackHistory() {
      const res = await returnHistory({ roNo: this.formData.roNo });
      if (res.resultCode === 200) {
        if (res.errMsg) {
          notifyAction(res.errMsg, 'error');
        } else {
          this.tableList = res.data;
        }
      }
    },
    // 获取维修类型
    async queryRepairTypeDict() {
      let res = await getWxlxSelect();
      if (res.resultCode == 200) {
        this.repairTypeList = res.data;
        let repairTypeDict = res.data.map(item => ({ text: item.REPAIR_TYPE_NAME, value: item.REPAIR_TYPE_CODE + '' }));
        this.repairTypeDict = repairTypeDict;
        let targetTableItems = [findTableItem(this.roHistoryColumns, 'REPAIR_TYPE_CODE')];
        targetTableItems.forEach(item => {
          item.dictItems = repairTypeDict;
        });
      }
    },
    // 获取工单历史
    async roHistoryListFun() {
      const res = await queryLocalRepairHistory({ vin: this.formData.vin });
      if (res.resultCode === 200) {
        if (res.errMsg) {
          notifyAction(res.errMsg, 'error');
        } else {
          this.roHistoryList = res.data.rows;
        }
      }
    },
    //获取问卷
    async getAnswer() {
      let param = { orderType: 50191001 };
      let res = await getAskAndAnswer(param);
      if (res.resultCode == 200) {
        let list = res.data.map(x => ({ text: x.WXWJMC, value: x.WXWJID }));
        this.formList.find(x => x.fieldName == 'chooseAnswer').itemList = list;
      }
    },
    tableDataChangeMeth(val) {
      this.tableDataChange = val;
    }
  }
};
</script>
<style lang="less" scoped></style>
